<?php

namespace app\zyhsapi\model;

use app\common\cachemodel\zlcr2\Zlcr2UserQuestion;
use app\common\cachemodel\ZlcrAstr;
use app\common\lib\Util;
use think\Env;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsAppFeedback extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_app_feedback';

    protected $cacheModel = 'zyhs.app_feedback';

    /**
     * 添加 反馈数据
     * @param array $data
     * @return int
     */
    public function SaveData(array $data)
    {
        try
        {
            if (isset($data['extend']) && $data['extend'] && is_array($data['extend']))
            {
                $data['extend'] = json_encode($data['extend'], JSON_UNESCAPED_UNICODE);
            }
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['uid'], [$id => $id], $data['app_type']);
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    /**
     * 获取当前用户是否有未读消息
     * @param int $appType
     * @param int $uid
     * @return bool
     * @throws \Exception
     */
    public function getHasUnread(int $appType, int $uid): bool
    {
        $numData = CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('has_unread', $appType . ':' . $uid)
            ->getDataAndSet(function () use ($appType, $uid)
            {
                try
                {
                    $num = $this->where(['app_type' => $appType, 'uid' => $uid, 'type' => 2, 'is_read' => 0])->count();
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $num = 0;
                }
                return ['unread_num' => $num];
            }, [], 'has_unread');

        return $numData['unread_num'] > 0 ? true : false;
    }

    /**
     * 更新未读消息 已读
     * @param int $appType
     * @param int $uid
     * @return void
     */
    public function msgRead(int $appType, int $uid)
    {
        try
        {
            // 获取未读消息 IDS
            $unreadIds = $this->where(['app_type' => $appType, 'uid' => $uid, 'type' => 2, 'is_read' => 0])->column('id');
            // 更新 未读消息 至 已读
            $this->where(['id' => ['in', $unreadIds]])->update(['is_read' => 1, 'read_time' => time()]);

            foreach ($unreadIds as $id)
            {   // 删除 缓存
                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            }
            CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('has_unread', $appType . ':' . $uid)->rmCache('has_unread');
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 获取列表数据
     * @param int $appType
     * @param int $uid
     * @param int $limit
     * @param int $maxId
     * @return array
     * @throws \Exception
     */
    public function getPageDatas(int $appType, int $uid, int $limit, int $maxId = 0)
    {
        if ($uid === 0)
        {
            return [
                'total' => 0,
                'surplus_num' => 0,
                'data' => [],
            ];
        }

        $idsData = CacheManageZyhs::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setListKeyType($appType)
            ->setPage(-1)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($appType, $uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'app_type' => $appType])->order("id {$sortType}")->column('id');

                    $resData = [];
                    foreach ($data as $id)
                    {
                        $resData[$id] = ['id' => $id];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'id', 0);

        arsort($idsData['data']);
        $allIds = array_keys($idsData['data']);
        $ids = [];
        $surplusNum = 0;
        foreach ($allIds as $idItem)
        {
            if ($maxId > 0 && $idItem >= $maxId) continue;

            if (count($ids) >= $limit)
            {
                $surplusNum++;
            } else
            {
                $ids[] = $idItem;
            }
        }
        $dataList = $this->batchGetInfoByIds($ids);
        asort($ids);

        $resDataList = [];
        if ($surplusNum === 0)
        {
            $resDataList[] = [
                'id' => 0,
                'type' => 2,
                'app_type' => $appType,
                'content' => '你好，可发送对应订单进行反馈，我会及时为你处理你的问题。工作时间：周一至周五10:00-18:00，回复可能存在延迟，请您耐心等待，感谢您的理解。',
                'content_type' => 1,
                'extend' => [],
                'create_time' => 0,
            ];
        }
        foreach ($ids as $idItem)
        {
            if (isset($dataList[$idItem]))
            {
                $resDataList[] = $dataList[$idItem];
            }
        }

        $resData = [
            'total' => count($allIds),
            'surplus_num' => $surplusNum,
            'data' => $resDataList,
        ];

        return $resData;
    }

    /**
     * 获取 反馈记录列表
     * @param int $appType
     * @param array $userInfo
     * @param int $minId
     * @return array
     * @throws \Exception
     */
    public function getFeedbackList(int $appType, array $userInfo, int $minId)
    {
        $data = $this->getPageDatas($appType, $userInfo['id'], 15, $minId);

        $data['data'] = $data['data'] ? $this->resDataResert($data['data'], $userInfo) : [];

        return $data;
    }

    /**
     * 数据重置
     * @param array $data
     * @param array $userInfo
     * @return array
     * @throws \Exception
     */
    public function resDataResert(array $data, array $userInfo)
    {
        $lastTime = 0;
        $resData = [];
        $now0Time = strtotime(date('Y-m-d')); // 今日0点时间
        $defaultAvatar = Env::get('host.photo') . '/zyhsapp/default_avatar.png';
        $questionTypeArr = [
            1 => '星盘',
            2 => '骰子',
            3 => '幸运卡牌',
        ];
        $zlcrAstrModel = new ZlcrAstr();
        $zyhsConsultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        foreach ($data as $datum)
        {
            $createTime = '';
            if ($datum['create_time'] - $lastTime > 300)
            {
                $createTime = $this->timeConvert($datum['create_time'], $now0Time);
            }
            $avatar = $datum['type'] === 1 ? $userInfo['avatar'] : $defaultAvatar;

            $msgDes = '';
            $serviceData = null;
            if ($datum['extend'] && isset($datum['extend']['type'], $datum['extend']['id']))
            {
                $msgDes = $datum['extend']['type'] === 1 ? '服务反馈-连线咨询' : '服务反馈-悬赏提问';
                $isCounslt = false;
                if (($datum['app_type'] === 1 && $datum['extend']['type'] === 1) || ($datum['app_type'] === 2 && $datum['extend']['type'] === 100))
                {
                    $isCounslt = true;
                }
                // 连线咨询
                if ($isCounslt)
                {
                    $serData = $zyhsConsultChatRtcRecordModel->getInfoById($datum['extend']['id']);
                    $durationTime = Util::secondToMinute($serData['duration']);
                    $astrInfo = $zlcrAstrModel->getInfoById($serData['astr_id'], ['nickname']);
                    $list = [
                        "咨询师：{$astrInfo['nickname']}",
                        "服务编号：{$serData['chat_detail_id']}",
                        "连线时长：{$durationTime}",
                    ];
                    $target = 'local';
                    $link = "chat_order_detail?id={$serData['chat_detail_id']}&need_auth=2";
                } else
                {
                    if ($datum['app_type'] === 1)
                    {
                        $userQuestionModel = new ZyhsUserQuestion();
                        // 悬赏提问
                        $serData = $userQuestionModel->getInfoById($datum['extend']['id']);
                        $questionType = $questionTypeArr[$serData['question_type']] . "-{$serData['receiving_num']}人回复";
                    } else
                    {
                        $userQuestionModel = new Zlcr2UserQuestion();
                        // 问答
                        $serData = $userQuestionModel->getInfoById($datum['extend']['id']);
                        $questionType = $questionTypeArr[$serData['question_type']];
                    }
                    $list = [
                        "问题：{$serData['question']}",
                        "服务编号：{$serData['order_num']}",
                        "问题类型：{$questionType}",
                    ];
                    $target = 'local';
                    $link = "question_detail?qid={$serData['id']}&need_auth=0";
                }
                $serviceData = [
                    'list' => $list,
                    'target' => $target,
                    'link' => $link,
                ];
            }
            if ($datum['type'] === 1)
            {
                $isRead = $datum['is_read'];
            } else
            {
                $isRead = -1;
            }
            $resData[] = [
                'id' => $datum['id'],
                'type' => $datum['type'],
                'time_des' => $createTime,
                'avatar' => $avatar,
                'msg_des' => $msgDes,
                'content' => $datum['content'],
                'content_type' => $datum['content_type'],
                'is_read' => $isRead,
                'service_data' => $serviceData,
            ];
            $lastTime = $datum['create_time'];
        }

        return $resData;
    }

    /**
     * 时间转换
     * @param int $time 待转换的时间
     * @param int $now0Time 今日零点时间
     * @return string
     */
    public function timeConvert(int $time, int $now0Time)
    {
        $t = $now0Time - $time;
        if ($t <= 0)
        {
            $timeStr = date('H:i', $time);
        } elseif ($t <= 86400)
        {
            $timeStr = date('昨日 H:i', $time);
        } else
        {
            $timeStr = date('m-d H:i', $time);
        }

        return $timeStr;
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            // 获取未删除 的数据
            $data = $this
                ->where(['id' => ['in', $ids]])
                ->column('id,uid,type,aid,content,content_type,extend,is_read,read_time,create_time,app_type', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'uid', 'aid', 'content_type', 'type', 'is_read', 'create_time', 'read_time', 'app_type']);

            if (isset($itemData['extend']))
            {
                $data[$index]['extend'] = $itemData['extend'] ? json_decode($itemData['extend'], true) : [];
            }
        }

        return $data;
    }
}
